
from Webpage import *
from TrafficRank import TrafficRank
from Graph import Graph
import numpy as np
from time import gmtime, strftime
# import mail

class Result(object):
	'''Class That Will Produce and Analyze Simulation Result'''

	def __init__(self):
		print 'Initialzing Result Object...'
		self.tr = TrafficRank()
		self.simDone = 0

	def __del__(self):
		print 'deleting Result Webpage...'

	def Sim(self, moduleName, version):
		self.moduleName = moduleName;
		self.version = version;
		addr = './data/'
		addr += moduleName

		print 'Version [2010]--'
		addr += '/index-tl.html'
		page = HistCiteWebpage2010(addr, moduleName)

		# Construct the topology accroding the info in webpage. 
		g = Graph(page.ItemNum)
		m = 0
		LCS = [{}] * page.ItemNum
		for a in range(page.ItemNum):
			item = page.GetItem(a+1)
			idx = item['id']
			if type(item['LCSSet']) is int:
				# print item
				g.AddLink(item['LCSSet'], idx)
				# g.AddLink(idx, item['LCSSet'])
			elif len(item['LCSSet']) >= 1:
				# print item
				for j in item['LCSSet']:
					# print j
					g.AddLink(j, idx)
					# g.AddLink(idx, j)

			LCS[m] = item['LCS']
			m += 1

		self.LCSRank = np.argsort(LCS)
		self.LCSRank = self.LCSRank[::-1] + 1

		try:
			self.tr.LoadGraph(g)
			self.tr.Exec()
			print 'Simulation Successful'
			self.simDone = 1
		except :
			print 'Simulation Failed! \n'
			self.simDone = 0


	def WriteRes2File(self, fileName):
		'''Write the Adjacent Matrix to a text file'''
		if self.simDone != 1:
			print 'Simulation Hasn''t been finished!'
			return
		f = open(fileName, "a+")

		# Write Down Basic Information Of Simulation
		rStr = ''
		rStr += 'Time: '
		rStr += strftime("%a, %d %b %Y %H:%M:%S +0000\n", gmtime()) 
		rStr += 'Module Name: [ '
		rStr += self.moduleName
		rStr += ' ] \n'
		rStr += 'Version: [ '
		rStr += str(self.version)
		rStr += ' ]\n'
		f.write(rStr) 


		# Write Down The Stationary Probability
		staProb = self.tr.GetStaProb()
		# print staProb.shape[1]
		# M = staProb.shape[1];
		M = staProb.shape[0];
		f.write(str(M)+'\n')

		# f.write(str(M)+'\n')
		f.write('Station Probability Distribution\n')
		string = '';
		for i in range(M):
			 string += str( staProb[i] ) 
			 string += '\t'
			 # import pdb
			 # pdb.set_trace()
			 # print staProb[i]
			 f.writelines(string)
		# f.write(str(M)+'\n') 
		f.write('\n')


		# Write Down the Rank
		f.write('Rank According to TrafficRank\n')
		rk = self.tr.GetRank()
		M = rk.shape[0]
		string =''
		for i in range(M):
			 string += str( rk[i] ) 
			 string += '\t'
			 # import pdb
			 # pdb.set_trace()
			 # print staProb[i]
			 f.writelines(string)
		f.write('\n')
		# f.write(str(M)+'\n') 
		# import pdb
		# pdb.set_trace()
		# print staProb[i]

		# Write Down RANK according to LCS
		f.write('Rank According to LCS\n')
		M = self.LCSRank.shape[0]
		string =''
		for i in range(M):
			 string += str( self.LCSRank[i] ) 
			 string += '\t'
			 # import pdb
			 # pdb.set_trace()
			 # print staProb[i]
			 f.writelines(string)
		f.write('\n')


		f.write('\n')
		f.close()


	def CalculateDiff(self):
		'''Compare the Rank of TrafficRank and LCS'''
		if self.simDone != 1:
			print 'Simulation Hasn''t been finished!'
			return
		
		staProb = self.tr.GetStaProb()
		rk = self.tr.GetRank()
		print self.LCSRank
		# rk == self.LCSRank
		num = 0;
		M = rk.shape[0]
		for i in range(M):
			if rk[i] == self.LCSRank[i]:
				num += 1
		ratio = float(num) / M
		print 'The ratio of consistence is ' + str(ratio)

		# import pdb
		# pdb.set_trace()
		# print staProb[i]

		return (M, num, ratio) 







